package com.lsf.modules.system.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsf.common.api.vo.Result;
import com.lsf.common.constant.CommonConstant;
import com.lsf.modules.base.service.BaseCommonService;
import com.lsf.modules.system.entity.User;
import com.lsf.modules.system.entity.UserRole;
import com.lsf.modules.system.mapper.UserRoleMapper;
import com.lsf.modules.system.service.UserRoleService;
import com.lsf.modules.system.service.UserService;
import com.lsf.modules.system.mapper.UserMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户
 *
 * @author Alexander
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private BaseCommonService baseCommonService;

    @Resource
    private UserRoleMapper userRoleMapper;

    @Override
    public Result<JSONObject> checkUserIsEffective(User user) {
        Result<JSONObject> result = new Result<>();
        //情况1：根据用户信息查询,该用户不存在
        if (user == null) {
            result.error500("用户不存在,请注册");
            baseCommonService.addLog("用户登陆失败,用户不存在!", CommonConstant.LOG_TYPE_1, null);
            return result;
        }
        //情况2：根据用户信息查询,该用户已注销
        if (CommonConstant.DEL_FLAG_1.equals(user.getDelFlag())) {
            result.error500("用户已注销");
            baseCommonService.addLog("用户登录失败,用户名：" + user.getUsername() + "已注销!", CommonConstant.LOG_TYPE_1, null);
            return result;
        }
        //情况3：根据用户信息查询,该用户已冻结
        if (CommonConstant.USER_FREEZE.equals(user.getStatus())) {
            result.error500("用户已被冻结");
            baseCommonService.addLog("用户登录失败,用户名：" + user.getUsername() + "已冻结!", CommonConstant.LOG_TYPE_1, null);
            return result;
        }
        result.setSuccess(true);
        return result;
    }

    @Override
    public User getUserByName(String username) {
        return userMapper.getUserByName(username);
    }

    @Override
    public User getUserByPhone(String phone) {
        return userMapper.getUserByPhone(phone);
    }

    @Override
    public User getUserByEmail(String email) {
        return userMapper.getUserByEmail(email);
    }

    @Override
    public void addUserWithRole(User user, String roleIds) {
        this.save(user);
        if (StringUtils.isNotEmpty(roleIds)) {
            String[] arr = roleIds.split(",");
            for (String roleId : arr) {
                UserRole userRole = new UserRole(user.getId(), roleId);
                userRoleMapper.insert(userRole);
            }
        }
    }
}




